package com.tensquare.user.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制器层
 *
 * @author Administrator
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JwtUtil jwtUtil;


    /**
     * 更新好友粉丝数和用户关注数
     *
     * @return
     */
    @RequestMapping(value = "/{userid}/{friendid}/{x}", method = RequestMethod.PUT)
    public void updatefanscountandfollowcount(@PathVariable String userid, @PathVariable String friendid, @PathVariable int x) {
        userService.updatefanscountandfollowcount(x, userid, friendid);
    }
    ///user/login

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody User user) {
        if (user == null) {
            return new Result(false, StatusCode.PARAM_NULL, "参数不能为空！");
        }
        if (user.getMobile() == null || user.getMobile().equals("")) {
            return new Result(false, StatusCode.PARAM_NULL, "手机号不能为空！");
        }
        if (user.getPassword() == null || user.getPassword().equals("")) {
            return new Result(false, StatusCode.PARAM_NULL, "密码不能为空！");
        }
        User user1 = userService.login(user);
        if (user1 == null) {
            return new Result(false, StatusCode.LOGINERROR, "用户名或密码错误，请重新登录！");
        }
        //生成token
        String token = jwtUtil.createJWT(user.getId(), user.getMobile(), "user");
        Map map = new HashMap();
        map.put("token", token);
        map.put("mobile", user1.getMobile());//登陆手机号
        map.put("name", user1.getNickname());//用户昵称
        map.put("avatar", user1.getAvatar());//头像
        map.put("id", user1.getId());
        //使得前后端可以通话的操作。采用JWT来实现
        return new Result(true, StatusCode.OK, "登录成功！", map);
    }

    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll() {
        return new Result(true, StatusCode.OK, "查询成功", userService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findById(id));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<User> pageList = userService.findSearch(searchMap, page, size);
        return new Result(true, StatusCode.OK, "查询成功", new PageResult<User>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(true, StatusCode.OK, "查询成功", userService.findSearch(searchMap));
    }

    /**
     * 增加用户
     *
     * @param user
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody User user) {
        userService.add(user);
        return new Result(true, StatusCode.OK, "增加成功");
    }

    /**
     * 修改
     *
     * @param user
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Result update(@RequestBody User user, @PathVariable String id) {
        user.setId(id);
        userService.update(user);
        return new Result(true, StatusCode.OK, "修改成功");
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id, HttpServletRequest request) {
        Claims claims = (Claims) request.getAttribute("admin_claims");
        if (claims == null) {
            return new Result(false, StatusCode.ACCESSERROR, "无权访问");
        }
        userService.deleteById(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }


    /**
     * user/sendsms/{mobile}
     * 发送手机验证码
     *
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/sendsms/{mobile}", method = RequestMethod.POST)
    public Result sendSMS(@PathVariable String mobile) {
        userService.sendSMS(mobile);
        return new Result(true, StatusCode.OK, "验证码发送成功！");
    }

    ///user/register/{code}
    //注册用户
    @RequestMapping(value = "/register/{code}", method = RequestMethod.POST)
    public Result register(@PathVariable String code, @RequestBody User user) {
        //redisTemplate.opsForValue().set("smscode_" + mobile, numeric + "", 5, TimeUnit.MINUTES);//五分钟过期
        if (user == null) {
            return new Result(false, StatusCode.PARAM_NULL, "参数不能为空！");
        }
        if (user.getNickname() == null || user.getNickname().equals("")) {
            return new Result(false, StatusCode.ERROR, "昵称或姓名不能为空！");
        }
        if (user.getPassword() == null || user.getPassword().equals("")) {
            return new Result(false, StatusCode.ERROR, "密码不能为空！");
        }
        if (user.getMobile() == null || user.getMobile().equals("")) {
            return new Result(false, StatusCode.ERROR, "手机号不能为空！");
        }

        String numeric = (String) redisTemplate.opsForValue().get("smscode_" + user.getMobile());//从redis中取出短信验证码
        if (numeric == null || numeric.equals("")) {
            return new Result(false, StatusCode.ERROR, "短信验证码错误或过期！");
        }
        if (!numeric.equals(code)) {
            //redisTemplate.delete("smscode_" + user.getMobile());//删除redis中的验证码
            return new Result(false, StatusCode.ERROR, "短信验证码错误或过期！");
        }
        userService.add(user);
        redisTemplate.delete("smscode_" + user.getMobile());//删除redis中的验证码
        return new Result(true, StatusCode.OK, "注册成功！");
    }
}
